package com.yipei.business.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yipei.business.domain.MlInvestmentProductOrder;
import com.yipei.business.domain.MlRealName;
import com.yipei.business.mapper.MlInvestmentProductOrderMapper;
import com.yipei.business.service.IMlInvestmentProductOrderService;
import com.yipei.business.service.IMlRealNameService;
import com.yipei.business.service.IMlTradeAccountService;
import com.yipei.common.core.domain.entity.MlTradeAccount;
import com.yipei.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 投资产品订单Service业务层处理
 *
 * @author yipei
 * @date 2025-07-14
 */
@Service
public class MlInvestmentProductOrderServiceImpl extends ServiceImpl<MlInvestmentProductOrderMapper, MlInvestmentProductOrder> implements IMlInvestmentProductOrderService {
    @Autowired
    private MlInvestmentProductOrderMapper mlInvestmentProductOrderMapper;
    @Autowired
    private IMlTradeAccountService iMlTradeAccountService;

    @Autowired
    private IMlRealNameService mlRealNameService;

    /**
     * 查询投资产品订单
     *
     * @param id 投资产品订单主键
     * @return 投资产品订单
     */
    @Override
    public MlInvestmentProductOrder selectMlInvestmentProductOrderById(Long id) {
        return mlInvestmentProductOrderMapper.selectMlInvestmentProductOrderById(id);
    }

    /**
     * 查询投资产品订单列表
     *
     * @param mlInvestmentProductOrder 投资产品订单
     * @return 投资产品订单
     */
    @Override
    public List<MlInvestmentProductOrder> selectMlInvestmentProductOrderList(MlInvestmentProductOrder mlInvestmentProductOrder) {
        return mlInvestmentProductOrderMapper.selectMlInvestmentProductOrderList(mlInvestmentProductOrder);
    }

    /**
     * 新增投资产品订单
     *
     * @param mlInvestmentProductOrder 投资产品订单
     * @return 结果
     */
    @Override
    public int insertMlInvestmentProductOrder(MlInvestmentProductOrder mlInvestmentProductOrder) throws Exception {
        String tdAcc = mlInvestmentProductOrder.getTdAcc();
        MlTradeAccount one = iMlTradeAccountService.lambdaQuery().eq(MlTradeAccount::getTdAcc, tdAcc).one();
        if (ObjectUtils.isEmpty(one)) {
            throw new Exception("交易账号不存在");
        } else {
            MlRealName realName = mlRealNameService.lambdaQuery().eq(MlRealName::getTdAcc, tdAcc).one();
            if (!ObjectUtils.isEmpty(realName)) {
                mlInvestmentProductOrder.setUserName(realName.getZsMz());
            }
        }
        mlInvestmentProductOrder.setCreateTime(DateUtils.getNowDate());
        mlInvestmentProductOrder.setOrderNumber(this.createrDH("TZ"));
        BigDecimal divide = mlInvestmentProductOrder.getDailyReturn().divide(new BigDecimal(100));
        BigDecimal yjSy = mlInvestmentProductOrder.getInvestAmount().multiply(divide).multiply(new BigDecimal(mlInvestmentProductOrder.getInvestmentCycle()));
        mlInvestmentProductOrder.setExpectedTotalRevenue(yjSy);
        return mlInvestmentProductOrderMapper.insertMlInvestmentProductOrder(mlInvestmentProductOrder);
    }

    public String createrDH(String dh) {
        Date date = new Date();
        DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String format = formatter.format(date);
        Random random = new Random();
        int randomNumber = random.nextInt(100000);
        String formattedNumber = String.format("%05d", randomNumber);
        String wtDh = dh + format + formattedNumber;
        return wtDh;
    }

    /**
     * 修改投资产品订单
     *
     * @param mlInvestmentProductOrder 投资产品订单
     * @return 结果
     */
    @Override
    public int updateMlInvestmentProductOrder(MlInvestmentProductOrder mlInvestmentProductOrder) {
        mlInvestmentProductOrder.setUpdateTime(DateUtils.getNowDate());
        return mlInvestmentProductOrderMapper.updateMlInvestmentProductOrder(mlInvestmentProductOrder);
    }

    /**
     * 批量删除投资产品订单
     *
     * @param ids 需要删除的投资产品订单主键
     * @return 结果
     */
    @Override
    public int deleteMlInvestmentProductOrderByIds(Long[] ids) {
        return mlInvestmentProductOrderMapper.deleteMlInvestmentProductOrderByIds(ids);
    }

    /**
     * 删除投资产品订单信息
     *
     * @param id 投资产品订单主键
     * @return 结果
     */
    @Override
    public int deleteMlInvestmentProductOrderById(Long id) {
        return mlInvestmentProductOrderMapper.deleteMlInvestmentProductOrderById(id);
    }

    @Override
    public void mlInvestmentProductOrder() {
        List<MlInvestmentProductOrder> mlInvestmentProductOrders = this.lambdaQuery().eq(MlInvestmentProductOrder::getStatus, "1").list();
        List<MlInvestmentProductOrder> mlInvestmentProductOrderList = mlInvestmentProductOrders.stream().filter(order -> {
            Date createTime = order.getCreateTime();
            if (createTime == null) return false;
            // 转为 LocalDateTime
            LocalDateTime createDateTime = createTime.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();

            // 当前时间
            LocalDateTime now = LocalDateTime.now();
            Long investmentCycle = Long.valueOf(order.getInvestmentCycle());
            // 判断：创建时间 + 30 天 <= 当前时间
            return !createDateTime.plusDays(investmentCycle).isBefore(now); // 即 <= now
        }).collect(Collectors.toList());
        for (MlInvestmentProductOrder mlInvestmentProductOrder : mlInvestmentProductOrderList) {
            BigDecimal multiply = mlInvestmentProductOrder.getInvestAmount().multiply((mlInvestmentProductOrder.getDailyReturn())).divide(new BigDecimal(100),4, RoundingMode.HALF_UP);
            BigDecimal income = mlInvestmentProductOrder.getIncome() == null ? BigDecimal.ZERO : mlInvestmentProductOrder.getIncome();
            mlInvestmentProductOrder.setIncome(multiply.add(income));
        }
        this.updateBatchById(mlInvestmentProductOrderList, 1000);
    }
}
